#include<stdio.h>
#include<pthread.h>
#include<unistd.h>

/*抢票 100 
 * 主线程 工作进程 工作线程
 * */

#define THREADCOUNT 2   // 两个人抢票
int g_tickets = 100;     // 定义一百张票
pthread_mutex_t g_lock;   // 互斥锁加锁接口

void* MyThreadStart(void* arg)
{
  while(1)
  {
    pthread_mutex_lock(&g_lock);   //阻塞加锁
    if(g_tickets > 0)
    {
      printf("i am %p,i have %d tickes\n",pthread_self(),g_tickets--);
    }
    else{
      pthread_mutex_unlock(&g_lock);   //解锁
      pthread_exit(NULL);            //线程终止
    }
    pthread_mutex_unlock(&g_lock);
  }
  return NULL;
}


int main()
{
  pthread_mutex_init(&g_lock,NULL);
  pthread_t tid[THREADCOUNT];    //定义数组形式
  int i=0;
  for (i ;i<THREADCOUNT;i++)
  {
    int ret = pthread_create(&tid[i],NULL,MyThreadStart,NULL);
    if(ret < 0)   //线程创建
    {
      perror("pthread_create");
      return 0;
    }
  }

  for(i = 0;i < THREADCOUNT;i++)
  {
    pthread_join(tid[i],NULL); // 线程等待
  }
  pthread_mutex_destroy(&g_lock);  //进程毁灭
  return 0;
}
